//
//  LogKeeper.m
//  Pocket Doctor alpha version
//
//  Created by Sherif Nosseir on 11-12-06.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//
//missing features:
//Sharing options - add "did you know" alert or something.


#import "AppDelegate.h"
#import "LogKeeper.h"

@implementation LogKeeper

@synthesize back, share, searchDate, logTracker, order, medicine, backtoLog, navDescription, description, descriptionImage, status, displayMedicine, displayStatus, descriptionsArray;
@synthesize aD, dinDB;


int clockSetting;
int dateSetting;
int daySetting;

NSString *medicineName, *logChange, *statusLog, *dateLogged;

- (IBAction)Back:(id)sender{
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)Share:(id)sender{
    UIActionSheet *options = [[UIActionSheet alloc]initWithTitle:@"What would you like to do?" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Message Logs", @"Email Logs", nil];
    
    [options showInView:self.view];
    [options release];
}

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //do send text (Message)
    }
    else
        if (buttonIndex == 1) {
            //do send email
        }
    
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
}

- (BOOL)isNumeric:(NSString *) s{
    NSScanner *sc = [NSScanner scannerWithString: s];
    if ( [sc scanFloat:NULL] )
    {
        return [sc isAtEnd];
    }
    return NO;
}

//Searching Scopes.
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    [displayMedicine removeAllObjects];
    [displayStatus removeAllObjects];
    
    if ([searchText length] == 0) {
        [displayMedicine addObjectsFromArray:self.medicine];
        [displayStatus addObjectsFromArray:self.status];
    }else{
            for (int i = 0; i<[medicine count]; i++) {
                NSString *medName = [medicine objectAtIndex:i];
                NSString *medStatus = [status objectAtIndex:i];
                
                NSRange r = [medName rangeOfString:searchText options:NSCaseInsensitiveSearch];
                if (r.location != NSNotFound) {
                    [displayMedicine addObject:medName];
                    [displayStatus addObject:medStatus];
                }else{
                    NSRange r = [medStatus rangeOfString:searchText options:NSCaseInsensitiveSearch];
                    if (r.location != NSNotFound) {
                        [displayMedicine addObject:medName];
                        [displayStatus addObject:medStatus];
                    }
                }
            }
        }
    
    [logTracker reloadData];
    
}

- (IBAction)BackToLog:(id)sender{
    
    description.text = @"";
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    //[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
    
    navDescription.alpha = 0;
    description.alpha = 0;
    descriptionImage.alpha = 0;
    
    [UIView commitAnimations];
}

/*How many rows are there in table view*/
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.displayMedicine count];
}

/*Selecting a row in the Table view will display an actionsheet*/
- (void) tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //decide what to do when clicking a certain medicine
    
    NSUInteger row = [indexPath row];
    NSUInteger len = [displayStatus count]-1;
    
    if ([order selectedSegmentIndex]==0) {
        
        NSString *temp = [[displayStatus objectAtIndex:len-row] substringToIndex:8];
        
        if ([temp isEqualToString:@"Modified"]) {
            
            description.text = [descriptionsArray objectAtIndex:len-row];
            
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:0.5];
            //[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
            
            navDescription.alpha = 1;
            description.alpha = 1;
            descriptionImage.alpha = 0.5;
            
            [UIView commitAnimations];
        }
    }else{
        
        NSString *temp = [[displayStatus objectAtIndex:row] substringToIndex:8];
        
        if ([temp isEqualToString:@"Modified"]) {
            
            description.text = [descriptionsArray objectAtIndex:row];
            
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:0.5];
            //[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
            
            navDescription.alpha = 1;
            description.alpha = 1;
            descriptionImage.alpha = 0.5;
            
            [UIView commitAnimations];
        }
    }
    
    //NSUInteger row = [indexPath row];
    [searchDate resignFirstResponder];
    [logTracker deselectRowAtIndexPath:indexPath animated:YES];
    
}

/*populates each cell in the table view*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimpleTableIdentifier] autorelease];
    }
    NSUInteger row = [indexPath row];
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if (daySetting==0 && clockSetting==0) {
        [dateFormatter setDateFormat:@"EEEE, h:mm a"];
    }else
        if (daySetting==0 && clockSetting ==1) {
            [dateFormatter setDateFormat:@"EEEE, H:mm"];
        }else
            if (daySetting==1 && clockSetting==0) {
                [dateFormatter setDateFormat:@"EEE, h:mm a"];
            }else{
                [dateFormatter setDateFormat:@"EEE, H:mm"];
            }
    
    
    NSDateFormatter *yearFormatter = [[NSDateFormatter alloc]init];
    if (dateSetting==0) {
        [yearFormatter setDateFormat:@"MMM/dd/yyy"];
    }else{
        [yearFormatter setDateFormat:@"dd/MMM/yyy"];
    }
    
    NSUInteger len = [displayStatus count]-1;
    
    if ([order selectedSegmentIndex]==0) {
        cell.textLabel.text = [displayMedicine objectAtIndex:len-row]; 
        cell.detailTextLabel.text = [displayStatus objectAtIndex:len-row];
    }else{
        cell.textLabel.text = [displayMedicine objectAtIndex:row]; 
        cell.detailTextLabel.text = [displayStatus objectAtIndex:row];
    }
    //textLabel will have medicine name
    //detailtextLabel will have Status + Date

    [dateFormatter release];
    return cell;
}

- (IBAction)ChangeOrder:(id)sender{
    [logTracker reloadData];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //modify to get real dates
    //Date Format!
    
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    NSMutableArray *arr2 = [[NSMutableArray alloc]init];
    NSMutableArray *arr3 = [[NSMutableArray alloc]init];
    
    NSString *subtitle;
    
    aD = [[UIApplication sharedApplication] delegate];
    
    NSString *dinDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"din.db"];
    sqlite3_open([dinDBPath UTF8String], &dinDB);
    
    sqlite3_stmt *statement;
    const char * query_stmt;
    NSString *loadSettings= @"SELECT clock_setting, date_setting, day_setting FROM Settings;";
    query_stmt = [loadSettings UTF8String];
    
    if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
        
        if (sqlite3_step(statement) == SQLITE_ROW){
            clockSetting = sqlite3_column_int(statement, 0);
            dateSetting = sqlite3_column_int(statement, 1);
            daySetting = sqlite3_column_int(statement, 2);
            
        }
    }
    
    [loadSettings release];
    
    NSString *loadLogs = @"SELECT * FROM MedicineLog;";
    query_stmt = [loadLogs UTF8String];
    
    if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
        
        while (sqlite3_step(statement) == SQLITE_ROW){
            //*medicineName, *logChange, *status, *dateLogged
            medicineName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
            logChange = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
            statusLog = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
            dateLogged = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
            
            /*NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            
            if (daySetting==0 && clockSetting==0) {
                [dateFormatter setDateFormat:@"EEEE, h:mm a"];
            }else
                if (daySetting==0 && clockSetting ==1) {
                    [dateFormatter setDateFormat:@"EEEE, H:mm"];
                }else
                    if (daySetting==1 && clockSetting==0) {
                        [dateFormatter setDateFormat:@"EEE, h:mm a"];
                    }else{
                        [dateFormatter setDateFormat:@"EEE, H:mm"];
                    }
            
            NSDateFormatter *yearFormatter = [[NSDateFormatter alloc]init];
            if (dateSetting==0) {
                [yearFormatter setDateFormat:@"MMM/dd/yyy"];
            }else{
                [yearFormatter setDateFormat:@"dd/MMM/yyy"];
            }*/
            
            //original dateLogged string : 2012-01-26 07:36:24 +0000
            if (dateSetting == 0){
                NSString *monthTemp = [[dateLogged substringFromIndex:5] substringToIndex:2];
                NSString *dayTemp = [[dateLogged substringFromIndex:8] substringToIndex:2];
                NSString *yearTemp = [[dateLogged substringFromIndex:0] substringToIndex:4];
                
                dateLogged = [[NSString alloc] initWithFormat:@"%@-%@-%@ %@", monthTemp, dayTemp, yearTemp, [dateLogged substringFromIndex:11]];
            }else{
                NSString *monthTemp = [[dateLogged substringFromIndex:5] substringToIndex:2];
                NSString *dayTemp = [[dateLogged substringFromIndex:8] substringToIndex:2];
                NSString *yearTemp = [[dateLogged substringFromIndex:0] substringToIndex:4];
                
                dateLogged = [[NSString alloc] initWithFormat:@"%@-%@-%@ %@", dayTemp, monthTemp, yearTemp, [dateLogged substringFromIndex:11]];
            }
            
            subtitle = [[NSString alloc]initWithFormat:@"%@ on %@", statusLog, dateLogged];
            
            [arr addObject:medicineName];
            [arr2 addObject:subtitle];
            [arr3 addObject:logChange];
        }
    }
    
    self.medicine = arr;
    self.status = arr2;
    self.descriptionsArray = arr3;
    
    NSMutableArray *displayMedicineObject = [[NSMutableArray alloc]initWithArray:medicine]; 
    NSMutableArray *displayStatusObject = [[NSMutableArray alloc]initWithArray:status];
    
    self.displayMedicine = displayMedicineObject;
    self.displayStatus = displayStatusObject;

    [arr release];
    [arr2 release];    
    [displayMedicineObject release];
    [displayStatusObject release];
    [subtitle release];
    
    [order setTintColor:[searchDate tintColor]];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
